const liveStream = document.getElementById('liveStream');
const recordButton = document.getElementById('recordButton');
const stopButton = document.getElementById('stopButton');
const closeButton = document.getElementById('closeButton'); // 获取关闭直播按钮

let mediaRecorder,Wstream;
let recordedChunks = [];
let uploadInterval;
let setRecording = false;
let ChunkIndex = 0
setVideo()
recordButton.addEventListener('click', async () => {
 const options = { mimeType: 'video/webm;codecs=vp9' };
 mediaRecorder = new MediaRecorder(Wstream, options);
 mediaRecorder.ondataavailable = event => {
  console.log("mediaRecorder.ondataavailable 开始录制");
  if (event.data.size > 0) {
   recordedChunks.push(event.data);
   uploadChunk(event.data); // 上传视频块
  }
 };
 mediaRecorder.start();
 recordButton.setAttribute("style", "display:none");
 console.log('mediaRecorder', mediaRecorder);
 console.log("mediaRecorder.state", mediaRecorder.state);
 // if (mediaRecorder.state === "recording") {
 //  mediaRecorder.resume();
 // }
 uploadInterval = setInterval(() => {
  if (recordedChunks.length > 0) {
   uploadChunk(recordedChunks.shift()); // 上传视频块
  }
 }, 1000); // 每1秒上传一次

 mediaRecorder.onpause = () => {
  console.log("mediaRecorder.onpause 暂停录制");
 };
 mediaRecorder.onstop = () => {
  const blob = new Blob(recordedChunks, { type: 'video/webm' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = 'recorded-video.webm';
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
   document.body.removeChild(a);
   URL.revokeObjectURL(url);
  }, 100);
 };
});

stopButton.addEventListener('click', () => {
 if (!setRecording) {
  alert("未开启直播");
  return
 }
 recordButton.setAttribute("style", "display:block");
 clearInterval(uploadInterval); // 停止上传
 mediaRecorder.pause();  // 暂停录制
});

// 添加关闭直播按钮的点击事件监听器
closeButton.addEventListener('click', () => {
 recordButton.setAttribute("style", "display:block");
 if (!setRecording) return;
 // 在这里实现关闭直播的逻辑
 // 例如，停止媒体流，释放资源等
 if (mediaRecorder && mediaRecorder.state === "recording") {
  mediaRecorder.stop();
 }
 if (liveStream.srcObject) {
  const tracks = liveStream.srcObject.getTracks();
  tracks.forEach(track => track.stop());
  liveStream.srcObject = null;
 }
 setRecording = false
 console.log("直播已关闭");
});

async function setVideo (cb) {
 if (setRecording) {
  cb && cb();
  return
 }
 setRecording = true;
 // 设置浏览器共享
 // navigator.mediaDevices.getDisplayMedia()
 // .then(devices => {
 //  console.log('可用设备:', devices);
 // })
 // 请求摄像头权限并获取媒体流
 navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
   liveStream.srcObject = stream;
   return new Promise(resolve => {
    liveStream.onloadedmetadata = () => {
     console.log('liveStream', liveStream);
     resolve(stream);
    };
   });
  })
  .then(stream => {
   Wstream = stream;
   cb && cb()
  })
  .catch(error => {
   setRecording = false
   console.error('无法访问摄像头:', error);
  });

}

function uploadChunk (chunk) {
 ChunkIndex++
 const formData = new FormData();
 formData.append('videoChunk', chunk, 'video.webm');
 // 直播间的id，默认是123456
 formData.append('videoId', '123456');
 formData.append('chunkIndex', ChunkIndex);
 fetch('/chatVideo/upload', {
  method: 'POST',
  body: formData
 })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
}